import Decorator from '../core/Decorator';
import { FAILURE, SUCCESS } from '../constants';
import Tick from '../core/Tick';
import BaseNode from '../core/BaseNode';

export default class Limiter extends Decorator {

  maxLoop: number
  constructor(child: BaseNode, maxLoop: number = 1) {
    super(`Limiter[${maxLoop}]`, child);
    this.addProperties('maxLoop', maxLoop)

    if (!maxLoop) {
      throw 'maxLoop parameter in Limiter decorator is an obligatory parameter';
    }

    this.maxLoop = maxLoop;
  }

  onOpen(tick: Tick, ...args: any[]) {
    tick.blackboard.set('i', 0, tick.tree.id, this.id);
  }

  onTick(tick: Tick, ...args: any[]) {

    var i = tick.blackboard.get('i', tick.tree.id, this.id);

    if (i < this.maxLoop) {
      var status = this.child.execute(tick, ...args);

      if (status == SUCCESS || status == FAILURE) {
        tick.blackboard.set('i', i + 1, tick.tree.id, this.id);
      }

      return status;
    }

    return FAILURE;
  }
};
